
import com.anhdt.model.Post;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PostService extends BaseService {
    public final String POST_ID="postID";
    public final String PAGE="page";
    public final String KEY="key";

    @Override
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        response.setContentType(TYPE_RP_JSON);
        try (PrintWriter out = response.getWriter()) {
            Post post = Post.getInstance();
            int id = Integer.parseInt(request.getParameter(POST_ID));
            out.println(this.ResponseJSon(post.getPostById(id)));
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        exeMethod(request, response);
    }

    protected void getLisForIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        response.setContentType(TYPE_RP_JSON);
        try (PrintWriter out = response.getWriter()) {
            Post post = Post.getInstance();
            out.println(this.ResponseJSon(post.getListPostForIndex()));
        }
    }

    protected void getListForSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        response.setContentType(TYPE_RP_JSON);
        String page = request.getParameter(PAGE);
        int pageNumber = 1;
        if (page != null && Integer.parseInt(page) > 1) {
            pageNumber = Integer.parseInt(page);
        }
        
        String key = request.getParameter(KEY);
        try (PrintWriter out = response.getWriter()) {
            Post post = Post.getInstance();
            out.println(this.ResponseJSon(post.search(key, pageNumber)));
        }
    }

}
